package com.system.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.common.context.LoginMemberContext;
import com.system.common.resp.PageResp;
import com.system.common.utils.SnowUtil;
import com.system.member.domain.Passenger;
import com.system.member.req.PassengerQueryReq;
import com.system.member.req.PassengerSaveReq;
import com.system.member.resp.PassengerQueryResp;
import com.system.member.service.PassengerService;
import com.system.member.mapper.PassengerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author Admin
* @description 针对表【passenger(乘车人)】的数据库操作Service实现
* @createDate 2024-03-18 13:29:31
*/
@Service
public class PassengerServiceImpl extends ServiceImpl<PassengerMapper, Passenger>
    implements PassengerService{

    @Autowired
    private PassengerMapper passengerMapper;

    @Override
    public void saveOrUpdate(PassengerSaveReq req) {
        DateTime now = DateTime.now();

        Passenger passenger = BeanUtil.copyProperties(req, Passenger.class);
        if (ObjectUtil.isNull(passenger.getId())) {
            passenger.setMemberId(LoginMemberContext.getId());
            passenger.setId(SnowUtil.getSnowflakeNextId());
            passenger.setCreateTime(now);
            passenger.setUpdateTime(now);
            passengerMapper.insert(passenger);
        } else {
            passenger.setUpdateTime(now);
            passengerMapper.updateById(passenger);
        }
    }

    @Override
    public PageResp<PassengerQueryResp> queryList(PassengerQueryReq req) {
        Page<Passenger> pageCondition = new Page<>(req.getPage(), req.getSize());
        QueryWrapper<Passenger> passengerQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(req.getMemberId())) {
            passengerQueryWrapper.eq("member_id",req.getMemberId());
        }
        Page<Passenger> pageData = passengerMapper.selectPage(pageCondition,passengerQueryWrapper);
        List<PassengerQueryResp> list = BeanUtil.copyToList(pageData.getRecords(), PassengerQueryResp.class);

        PageResp<PassengerQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageData.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    @Override
    public List<PassengerQueryResp> queryMine() {
        QueryWrapper<Passenger> passengerQueryWrapper = new QueryWrapper<>();
        passengerQueryWrapper.eq("member_id",LoginMemberContext.getId());
        List<Passenger> passengers = passengerMapper.selectList(passengerQueryWrapper);
        return BeanUtil.copyToList(passengers, PassengerQueryResp.class);
    }
}




